package com.hulk.dryad.manage.framework.websocket.client.support;

import cn.hutool.core.util.ObjectUtil;
import com.hulk.dryad.common.util.JacksonUtil;
import com.hulk.dryad.manage.framework.websocket.client.config.WebSocketClientClusterProperties;
import com.hulk.dryad.manage.framework.websocket.client.core.WsClient;
import com.hulk.dryad.manage.framework.websocket.common.message.WsMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import java.nio.charset.StandardCharsets;

/**
 * redis 消息发布
 *
 * @author
 */
@Slf4j
@RequiredArgsConstructor
public class RedisWsClientImpl implements WsClient {
	private final RedisTemplate<Object, Object> redisTemplate;
	private final WebSocketClientClusterProperties properties;

	@Override
	public void send(WsMessage message) {
		// 拼接 topic name
		String redisSubTopic = getRedisSubTopic(properties);
		log.info("websocket redis pub topic:{}", redisSubTopic);
		byte[] rawChannel = redisSubTopic.getBytes(StandardCharsets.UTF_8);
		// 自己的 json 序列化避免问题
		//byte[] rawMessage = JacksonUtil.toJsonAsBytes(message);
		byte[] rawMessage = ObjectUtil.serialize(message);
		// publish
		redisTemplate.execute(connection -> connection.publish(rawChannel, rawMessage), true);
	}

	private static String getRedisSubTopic(WebSocketClientClusterProperties properties) {
		return properties.getRedisSubTopicPrefix() + properties.getServerAppName();
	}

}
